import camelCase from "camelcase";
import _ from "lodash";
import PropTypes from "prop-types";
import React, { Component } from "react";
import { connect } from "react-redux";
import { View, StyleSheet, TouchableOpacity, Text, FlatList, Image, RefreshControl, Dimensions } from "react-native";
import { Utils,TopBar } from "tuya-panel-kit";
import TYSdk from "../../api";
import dpCodes from "../../config/dpCodes";
import Strings from "../../i18n";
import Res from "../../res";
import { debounce } from "../../utils";
import iconPageNodataLight from "../../res/icon-page-no-data-light.png";


const {
} = dpCodes;

class FeedRecordScene extends Component {

  static defaultProps = {
    dpState: {},
  };

  constructor(props) {
    super(props);
    // {"feed-operation":0,"feed-target-num":1,"feed-success-num":1,"feed-time":1716390994,"code":0,"today-feeded-num":1}
    // {"feed-operation":0,"feed-target-num":0,"feed-success-num":0,"feed-time":0,"code":0,"today-feeded-num":0}
    // feed-operation/喂食操作方式 0: Device 1: Net
    // feed-target-num/喂食目标份数 1-100
    // feed-success-num/喂食成功份数 0-100
    // feed-time/喂食当前时间 1-4294967295
    // code / 错误码 0: Success 1: Timeout 2: Turn Off
    // today-feeded-num/今日喂食份数 0-255

    this.state = {
      timers: null,
      devID: null,
      devType: "0",
      isEditing: false,
      records: [],
      isShowNodata: false,
      refreshing: false,
      showTop:true,
    };
  }

  async componentDidMount() {
    try {

      this.refreshData();

    } catch (err) {
      console.warn(err);
    }
  }

  refreshData = debounce(async () => {

    const recordArr = await TYSdk.getFeedRecordList();

    let isShowNodata = false;
    if (recordArr.length === 0) {
      isShowNodata = true;
    }
    this.setState({
      records: recordArr,
      isShowNodata: isShowNodata,
    });
  });

  onRefresh = debounce(async () => {

    this.setState({refreshing: true});

    const recordArr = await TYSdk.getFeedRecordList();

    setTimeout(() => {
      // 2秒后执行的代码
      console.log('2秒已过，执行操作');
      // 你可以在这里执行你的代码，比如更新state或者导航到另一个页面
      this.setState({
        records: recordArr,
        isShowNodata: recordArr.length === 0,
        refreshing: false,
      });
    }, 2000);

  });


  cellView(item, index) {

    return (
      <TouchableOpacity
        style={styles.cell}
        onPress={() => {

        }}
      >
        <View style={styles.tips}>
          <View style={styles.twoLines}>
            <Text style={styles.cellTitle}>{item.name}</Text>
            <Text style={[styles.cellTitle, { fontWeight: "normal", fontSize: 13, marginTop: 5 }]}>
              {item.timeStr}
            </Text>
          </View>
        </View>

        <Text style={[styles.cellTitle, { fontWeight: "normal", fontSize: 13, marginTop: 5 }]}>
          {item.count}
        </Text>

      </TouchableOpacity>
    );
  }


  bottomView() {
    const { isShowNodata } = this.state;
    return (
      <View style={{
        // backgroundColor: "#FFFFFF",
        height: 80,
        // flexDirection: "column",
        alignItems: "center",
        // justifyContent: "space-between",
        marginBottom: 20,
        paddingTop: 20,
        // opacity: !isShowNodata ? 1 : 0,
      }}>
        <Text style={{ fontSize: 13, color: "#333333" }}>{Strings.feeding_record_max_count_desc}</Text>
      </View>
    );
  }

  nodataView() {

    return (
      <View style={{
        // backgroundColor: "#FFFFFF",
        height: 80,
        width: 80,
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        position: 'absolute',
        marginTop: Dimensions.get('window').height*0.4-40,
        marginLeft: Dimensions.get('window').width*0.5-40,
      }}>
        <Image style={{}} resizeMode="cover" source={Res.iconPageNodataLight} />
        <Text style={{ fontSize: 14, color: "#333333" }}>{Strings.list_empty_title_feeding_record}</Text>
      </View>
    );
  }

  spaceView() {
    return (
      <View style = {{ height: 86 }}></View>
    );
  }

  listView(records, renderItem) {
    const { refreshing } = this.state;
    return (
      <FlatList
        style={{ height: 200 }}
        data={records}
        renderItem={renderItem}
        keyExtractor={(item, index) => index.toString()}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={this.onRefresh}
            colors={['blue', 'green', 'red']} // 可以定义刷新进度条的颜色
            tintColor="gray" // 刷新进度条的颜色
            title={Strings.card_loading}// 下拉时显示的文本
            titleColor="#999999" // 文本的颜色
          />
        }
      />
    );
  }

  topView() {
    return (
      <TopBar.Container
        background="#FFFFFF"
        style={{ height: TopBar.height }}
        contentStyle={{ height: TopBar.height, marginTop: 10 }}
      >
        <TopBar.Action size={20} source={Res.fback} color="#4C4C4C" onPress={() => TYSdk.Navigator.pop()} />
        <TopBar.Content />
      </TopBar.Container>
    );
  }

  render() {
    const { records, showTop, isShowNodata } = this.state;
    const renderItem = ({ item, index }) => (this.cellView(item, index));

    return (
      <View style={[styles.container]}>

        {showTop ? this.topView() : null}

        <View style={{ flex: 1, flexDirection: "column", justifyContent: "space-between" }}>
          <Text style={{
            paddingTop: 40,
            paddingBottom: 40,
            paddingLeft: 30,
            fontSize: 30,
            color: "#333333"
          }}>{Strings.page_title_feeding_record}</Text>


          {/* 喂食记录列表 */}
          { this.listView(records, renderItem) }

          {isShowNodata ? this.nodataView() : null }

          {!Array.isArray(records) || records.length === 0 ? this.spaceView() : this.bottomView()}

        </View>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    // justifyContent: 'space-between',
  },
  tips: {
    justifyContent: "space-between",
    flexDirection: "row"
  },
  cell: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: "#fff",
    height: 60,
    marginStart: 30,
    marginEnd: 10,
    marginTop: 10,
    // width: '100%',
    borderRadius: 12
  },
  oneLine: {
    flexDirection: "row",
    alignItems: "stretch"
  },
  twoLines: {
    flexDirection: "column",
    alignItems: "stretch"
  },
  cellTitle: {
    fontSize: 16,
    fontWeight: "bold",
    color: "#000"
  },
  icon: {
    justifyContent: "center",
    marginStart: 20,
    width: 40,
    height: 40
  },
  floatingContainer: {// 悬浮右下角
    position: "absolute",
    right: 30,
    bottom: 50,
    width: 50,
    height: 50,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 25
  },
  addBtn: {
    marginRight: 0,
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: "#22a8dc"
  },
  addBtnIcon: {
    width: 50,
    height: 50
  }
});

export default connect(({ dpState }) => ({
  dpState,
}))(FeedRecordScene);
